package routes

import (
	_ "GoWebBluebell/docs" // 千万不要忘了导入把你上一步生成的docs

	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	"GoWebBluebell/controllers"
	"GoWebBluebell/logger"
	"GoWebBluebell/middlewares"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

func Setup() *gin.Engine {
	// 初始化gin框架内置的效验器使用的翻译器
	if err := controllers.InitTrans("zh"); err != nil {
		fmt.Printf("init trans failed, err:%v\n", err)
	}

	if viper.GetString("mode") == gin.ReleaseMode {
		gin.SetMode(gin.ReleaseMode)
	}

	r := gin.New()
	r.Use(logger.GinLogger(), logger.GinRecovery(true), middlewares.RateLimitMiddleware(2, 1))

	r.GET("/swagger6/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	v1 := r.Group("api/v1")

	// 注册业务路由
	v1.POST("/signup", controllers.SignUpHandler)
	// 登录
	v1.POST("/login", controllers.LoginHandler)

	v1.Use(middlewares.JWTAuthMiddleware()) //应用JWT认证中间件
	{
		v1.GET("/community", controllers.CommunityHandler)
		v1.GET("/community/:id", controllers.CommunityDetailHandler)

		v1.POST("/post", controllers.CreatePostHandler)
		v1.GET("/post/:id", controllers.PostDetailHandler)
		v1.GET("/posts", controllers.GetPostListHandler)
		// 根据时间或分数或分社区获取帖子列表
		v1.GET("/posts2", controllers.GetPostListHandler2)

		// 投票
		v1.POST("/vote", controllers.PostVoteController)
	}

	r.NoRoute(func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"msg": 404,
		})
	})

	return r
}

//注册业务路由 -->controllers层(1.获取参数和参数校验2.业务处理(放入logic层)3.返回响应)
// --> logic层(判断用户是否存在; 生成UID; 保存进数据库) --> dao层 查重; 执行SQL语句入库
//层层递推(多写备注)
